package com.sgb.kjwl.viewmodel.self;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.AllFunction;
import com.sgb.kjwl.model.entity.MyCarInfoEntity;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.self.EnergyTypeEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.EntityConversion;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddCarInfoModel extends AndroidViewModel {
    public ObservableField<CarInfoEntity> carInfoEntity = new ObservableField<>(new CarInfoEntity());
    public MutableLiveData<String> uploadImg = new MutableLiveData<>();
    public MutableLiveData<Integer> uploadImgType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> CarsTypeData = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> CarsLengthData = new MutableLiveData<>();
    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> AddressData = new MutableLiveData<>();
    public MutableLiveData<CarInfoEntity> CarInfo = new MutableLiveData<>();
    public MutableLiveData<List<AllFunction>> MyCarList = new MutableLiveData<>();
    public MutableLiveData<List<EnergyTypeEntity>> energyTypeList = new MutableLiveData<>();
    public MutableLiveData<String> SubMit = new MutableLiveData<>();


//    public AddCarInfoModel(AddCarInfoActivity addCarInfoActivity, SelfRepertory repertory) {
//        this.activity = addCarInfoActivity;
//        this.repertory = repertory;
//    }
    public AddCarInfoModel(@NonNull Application application) {
        super(application);
    }
    //上传图片
    public void uploadMutiFileModel(Context context,File file, int type) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" +  "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if(response==null||response.body()==null){
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    uploadImgType.postValue(type);
                    uploadImg.postValue(response.body().getData().toString());
                  // activity.uploadImgSuccess(response.body().getData().toString(), type);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(context, t.getMessage());
            }
        });
/*        APIManager.getInstance().getDriverAPI().uploadWalkPermit(photos,type==1?1:0).enqueue(new Callback<BaseEntity<VehicleLicenseInfo>>() {
            @Override
            public void onResponse(Call<BaseEntity<VehicleLicenseInfo>> call, Response<BaseEntity<VehicleLicenseInfo>> response) {
                DialogHelper.dismissProgressDialog();
                if(response.body()==null){
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadImgSuccess(response.body().getData(), type);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<VehicleLicenseInfo>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });*/
    }
    //车类型
    public void getCarsType() {
        String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.CarTypeAndLen, "");
        if (!TextUtils.isEmpty(json)) {
           List<GoodsInfoTypeEntity3> data = new Gson().fromJson(json, new TypeToken<List<GoodsInfoTypeEntity3>>() {
            }.getType());
            CarsTypeData.postValue(data);
          //  activity.getCarsTypeData(data);
        }
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if(data.getState().equals("ok")&&data.getData()!=null) {
                    //获取全部车长并填充数据
                    String cacheMateialistlHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CarTypeAndLen);
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (!cacheMateialistlHash.equals(mHashNet)) {
                        CarsTypeData.postValue(data.getData());
                       // activity.getCarsTypeData(data.getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CarTypeAndLen, data.getData());
                    }

                }
            }
        });
    }


    //车长度
    public void getCarsLength(String carTypeNo) {
        String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.CarLen, "");
        if (!TextUtils.isEmpty(json)) {
            List<GoodsInfoTypeEntity3> data = new Gson().fromJson(json, new TypeToken<List<GoodsInfoTypeEntity3>>() {
            }.getType());
            CarsLengthData.postValue(data);
           // activity.getCarsLengthData(data);
        }
        NewAPIManager.getInstance().getLogisticsAPI().getCarLenByType(carTypeNo).enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {

                    String cacheMateialistlHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CarLen);
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(response.body().getData());
                    if (!cacheMateialistlHash.equals(mHashNet)) {
                        CarsLengthData.postValue(response.body().getData());
                        //activity.getCarsLengthData(response.body().getData());
                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CarLen, response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }
    //区域
    public void getAddressModel(Context context) {
        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                AddressData.postValue(response.body().getData());
               // activity.initAddressData(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
    public void getCarDetail(Context context,long no){
        DialogHelper.showProgressDialog(context, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getJingDriverDetail(no).enqueue(new Callback<BaseEntity<MyCarInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MyCarInfoEntity>> call, Response<BaseEntity<MyCarInfoEntity>> response) {
                DialogHelper.dismissProgressDialog();

                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    CarInfo.postValue(EntityConversion.modelA2B(response.body().getData(), CarInfoEntity.class));
                   // activity.setCarInfo(EntityConversion.modelA2B(response.body().getData(), CarInfoEntity.class));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MyCarInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }
    public void getCarFuncation(){
        NewAPIManager.getInstance().getLogisticsAPI().getCarFunction02().enqueue(new Callback<BaseEntity<List<AllFunction>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AllFunction>>> call, Response<BaseEntity<List<AllFunction>>> response) {
                if (response.body() == null) return;
                MyCarList.postValue(response.body().getData());
               // activity.setMyCarList(response.body().getData());
            }
            @Override
            public void onFailure(Call<BaseEntity<List<AllFunction>>> call, Throwable t) {

            }
        });
    }
    public void getCarEnergy (){
        NewAPIManager.getInstance().getLogisticsAPI().getCarEnergyType().enqueue(new Callback<BaseEntity<List<EnergyTypeEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<EnergyTypeEntity>>> call, Response<BaseEntity<List<EnergyTypeEntity>>> response) {
                energyTypeList.postValue(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<EnergyTypeEntity>>> call, Throwable t) {

            }
        });
    }
    public void authCar(Context context){
        DialogHelper.showProgressDialog(context, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        Map<String, Object> requestUtil = new HashMap<>();
        if(carInfoEntity.get().getId()!=0) {
            requestUtil.put("id", carInfoEntity.get().getId());
        }
        requestUtil.put("telphone",carInfoEntity.get().getTelphone());
        requestUtil.put("carTypeNo",carInfoEntity.get().getCarTypeNo());
        requestUtil.put("carLenNo",carInfoEntity.get().getCarLenNo());
        requestUtil.put("weight",carInfoEntity.get().getWeight());
        requestUtil.put("licensePlateColor",carInfoEntity.get().getLicensePlateColor());
        requestUtil.put("provinceNo",carInfoEntity.get().getProvinceNo());
        requestUtil.put("provinceName",carInfoEntity.get().getProvinceName());
        requestUtil.put("cityNo",carInfoEntity.get().getCityNo());
        requestUtil.put("cityName",carInfoEntity.get().getCityName());
        requestUtil.put("districtNo",carInfoEntity.get().getDistrictNo());
        requestUtil.put("districtName",carInfoEntity.get().getDistrictName());
        requestUtil.put("detailAddress",carInfoEntity.get().getDetailAddress());
        requestUtil.put("longitude",carInfoEntity.get().getLongitude());
        requestUtil.put("latitude",carInfoEntity.get().getLatitude());
        requestUtil.put("carImage",carInfoEntity.get().getCarImage());
        if (carInfoEntity.get().getAcquireTime() != 0) {
            requestUtil.put("acquireTime", carInfoEntity.get().getAcquireTime());
        }
        if(!TextUtils.isEmpty(carInfoEntity.get().getMainCertificate())){
            requestUtil.put("mainCertificate",carInfoEntity.get().getMainCertificate());
        }else{
            requestUtil.put("mainCertificate","");
        }
        if(!TextUtils.isEmpty(carInfoEntity.get().getViceCertificate())){
            requestUtil.put("viceCertificate",carInfoEntity.get().getViceCertificate());
        }else{
            requestUtil.put("viceCertificate","");
        }


        if(!TextUtils.isEmpty(carInfoEntity.get().getTransportCertificateMain())) {
            requestUtil.put("transportCertificateMain", carInfoEntity.get().getTransportCertificateMain());
        }else{
            requestUtil.put("transportCertificateMain", "");
        }
        if(!TextUtils.isEmpty(carInfoEntity.get().getTransportCertificateVice())){
            requestUtil.put("transportCertificateVice", carInfoEntity.get().getTransportCertificateVice());
        }else{
            requestUtil.put("transportCertificateVice","");
        }
        if(!TextUtils.isEmpty(carInfoEntity.get().getTransportCertificateNum())){
            requestUtil.put("transportCertificateNum", carInfoEntity.get().getTransportCertificateNum());
        }else{
            requestUtil.put("transportCertificateNum", "");
        }
        requestUtil.put("heightHurdle",carInfoEntity.get().getHeightHurdle());
        if (carInfoEntity.get().getIsDump()!=null){
            requestUtil.put("isDump",carInfoEntity.get().getIsDump());
        }
        requestUtil.put("imageSourceCode",carInfoEntity.get().getImageSourceCode());
        requestUtil.put("imageIssuingAuthority",carInfoEntity.get().getImageIssuingAuthority());
        requestUtil.put("functionNos",carInfoEntity.get().getFunctionNo());
        requestUtil.put("carProvinceName",carInfoEntity.get().getCarProvinceName());
        requestUtil.put("carProvinceNo",carInfoEntity.get().getCarProvinceNo());
        requestUtil.put("carCityName",carInfoEntity.get().getCarCityName());
        requestUtil.put("carCityNo",carInfoEntity.get().getCarCityNo());
        requestUtil.put("carDistrictName",carInfoEntity.get().getCarDistrictName());
        requestUtil.put("carDistrictNo",carInfoEntity.get().getCarDistrictNo());
        requestUtil.put("insuranceTime",carInfoEntity.get().getInsuranceTime());
        requestUtil.put("annualInspectionTime",carInfoEntity.get().getAnnualInspectionTime());
        requestUtil.put("upMaintainTime",carInfoEntity.get().getUpMaintainTime());
        requestUtil.put("intentionProvinceNo",carInfoEntity.get().getIntentionProvinceNo());
        requestUtil.put("intentionProvinceName",carInfoEntity.get().getIntentionProvinceName());
        requestUtil.put("intentionCityNo",carInfoEntity.get().getIntentionCityNo());
        requestUtil.put("intentionCityName",carInfoEntity.get().getIntentionCityName());
        if (carInfoEntity.get().getCarYears()==null){
            requestUtil.put("carYears",0);
        }else {
            requestUtil.put("carYears",carInfoEntity.get().getCarYears());
        }

        NewAPIManager.getInstance().getLogisticsAPI().authCar(requestUtil).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if(response.body()==null){
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_CARINFO_COMMIT));
                    SubMit.postValue(null);
                    //activity.finish();

                    MToast.showToast(context, "提交成功");

                }else{
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(context, t.getMessage());
            }
        });

    }
}
